import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from book.models import BookInfo


class BooksView(View):

    def post(self, request):
        # 接收
        data = json.loads(request.body.decode())
        btitle = data.get('btitle')
        bpub_date = data.get('bpub_date')

        # 验证
        if not all([btitle, bpub_date]):
            return JsonResponse({'error':'参数错误'}, status=400)

        # 处理
        BookInfo.objects.create(btitle=btitle, bpub_date=bpub_date)

        # 响应
        return JsonResponse({
            'btitle': btitle,
            'bpub_date': bpub_date
        }, status=200)

    def get(self, request):
        books = BookInfo.objects.all()
        books = [{'btitle': book.btitle, 'bpub_date': book.bpub_date} for book in books]
        return JsonResponse(books, safe=False, status=200)


class BookView(View):

    def get(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '图书没找到'}, status=404)

        return JsonResponse({
            'btitle': book.btitle,
            'bpub_date': book.bpub_date
        }, status=200)

    def delete(self, request, pk):
        BookInfo.objects.filter(id=pk).delete()
        return JsonResponse({'error': '删除成功'}, status=200)

    def put(self, request, pk):
        # 接收
        data = json.loads(request.body.decode())
        btitle = data.get('btitle')
        bpub_date = data.get('bpub_date')

        # 验证
        if not all([btitle, bpub_date]):
            return JsonResponse({'error': '参数错误'}, status=400)

        # 处理
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '图书没找到'}, status=404)

        book.btitle = btitle
        book.bpub_date = bpub_date
        book.save()

        # 相应
        return JsonResponse({
            'btitle': btitle,
            'bpub_date': bpub_date
        }, status=200)
